import axios from 'axios' // 引入axios
import { showToast, showLoadingToast, closeToast } from 'vant';
import { useUserStore } from '@/pinia/modules/user'
import router from '@/router/index'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 999999
})
let activeAxios = 0
let timer
// let loadingInstance
const showLoading = (option = {
  target: null,
}) => {
  activeAxios++
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    if (activeAxios > 0) {
      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
      });
    }
  }, 400)
}

const closeLoading = () => {
  activeAxios--
  if (activeAxios <= 0) {
    clearTimeout(timer)
    closeToast()
  }
}
// http request 拦截器
service.interceptors.request.use(
  config => {
    if (!config.donNotShowLoading) {
      showLoading(config.loadingOption)
    }
    const userStore = useUserStore()
    config.headers = {
      'Content-Type': 'application/json',
      'x-token': userStore.token,
      'x-user-id': userStore.userInfo.ID,
      ...config.headers
    }
    return config
  },
  error => {
    if (!error.config.donNotShowLoading) {
      closeLoading()
    }
    showToast(error)
    return error
  }
)

// http response 拦截器
service.interceptors.response.use(
  response => {
    const userStore = useUserStore()
    if (!response.config.donNotShowLoading) {
      closeLoading()
    }
    if (response.headers['new-token']) {
      userStore.setToken(response.headers['new-token'])
    }
    if (response.data.code === 0 || response.headers.success === 'true') {
      if (response.headers.msg) {
        response.data.msg = decodeURI(response.headers.msg)
      }
      return response.data
    } else {
      showToast(response.data.msg || decodeURI(response.headers.msg))
      return response.data.msg ? response.data : response
    }
  },
  error => {
    if (!error.config.donNotShowLoading) {
      closeLoading()
    }

    if (!error.response) {
      showToast(`${error}，请求报错`)
      return
    }

    switch (error.response.status) {
      case 500:
        showToast(`${error}，请求报错500`)
        break
      case 404:
        showToast(`${error}，接口不存在404`)
        break
      case 401:
        showToast(`无效的令牌`)
        const userStore = useUserStore()
        userStore.ClearStorage()
        router.push({ name: 'Login', replace: true })
        break
    }

    return error
  }
)
export default service
